/*
 * @Author: hongbin
 * @Date: 2022-11-03 12:59:51
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-20 22:30:59
 * @Description:添加用户
 */
import { NextApiRequest, NextApiResponse } from "next";
import { VerifyFields } from "../../src/api/utils";
import DB from "./mongodb";
import { AllowCORS } from "./utils";

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
    const db = await DB;
    await AllowCORS(req, res);
    switch (req.method) {
        case "POST":
            console.log(req.body);
            if (req.body.toString() !== "[object Object]") return res.json("错误body");
            if (!VerifyFields.has(req.body, ["name", "password", "mail"])) {
                return res.status(500).json("缺少关键字段");
            }
            const userInfo = { ...req.body };
            const insert = await db.collection("userInfo").insertOne(userInfo);
            console.log(insert);
            if (insert.acknowledged) {
                res.status(200).json({ data: insert.insertedId });
            } else res.status(500).json({ data: "添加失败" });
            break;
        case "GET":
            const list = await db.collection("userInfo").find({}).toArray();
            console.log(list);
            res.json({ data: list });
            break;
        default:
            res.json({ data: `未设置${req.method}请求方式` });
    }
}
